package gui;

import java.awt.Color;

import javax.swing.JLabel;
import javax.swing.JProgressBar;

import main.Terminal;
import model.Movie;

public class MovieProgress extends Thread{

	private Movie movie;
	private final int COMMERCIAL_TIME = 7;
	private final int TRAILER_TIME = 4;
	private JProgressBar progBar;
	private JLabel label;
	private JLabel maxTime;
	private int minutes;
	private int seconds;
	private int hours;
	boolean finish = false;
	int i = 0;
	int i2 = 0;
	
	public MovieProgress(Movie movie, JProgressBar progBar, JLabel label, JLabel maxTime)
	{
		this.movie = movie;
		this.progBar = progBar;
		minutes = COMMERCIAL_TIME;
		seconds = 0;
		this.label = label;
		this.maxTime = maxTime;
		
		while(seconds>= 60) {
			minutes++;
			seconds -= 60;
		}
		
		while(minutes>=60) {
			hours++;
			minutes -= 60;
		}
	}
	
	private void timeKeeper()
	{
		if(hours == 0 && minutes == 0 && seconds == 0)
		{
			if(i2 == 2)
			{
				label.setText("Done");
				finish = true;
			}
			if(i2 == 1)
			{
				progBar.setMaximum((movie.getLenght() * 60)); //<-- seconds, not minute
				progBar.setForeground(Color.green);
				progBar.setValue(0);
				minutes = movie.getLenght();
				while(minutes>60) {
					hours++;
					minutes -= 60;
				}
				maxTime.setText("" + movie.getLenght());
				i2++;
			}
			if(i2 == 0)
			{
				progBar.setMaximum((TRAILER_TIME * 60)); //<-- seconds, not minute
				progBar.setForeground(Color.yellow);
				progBar.setValue(0);
				minutes = TRAILER_TIME;
				maxTime.setText("" + TRAILER_TIME);
				i2++;
			}			
		}
		if(seconds == 0)
		{
			if(minutes > 0)
			{
				seconds = 60;
				minutes -= 1;
			}
		}
		if(minutes == 0)
		{
			if(hours > 0)
			{
				hours -= 1;
				minutes = 60;
			}
		}
		
	}
	
	@Override
	public void run() 
	{
		progBar.setMinimum(0);
		progBar.setValue(0);
		progBar.setMaximum((COMMERCIAL_TIME * 60)); //<-- seconds, not minute
		progBar.setForeground(Color.red);
		maxTime.setText("" + COMMERCIAL_TIME);	
		
		while(!finish) {			
			try {
				Thread.sleep(1000);
				this.progBar.setValue(progBar.getValue() + 1);
				label.setText(hours + ":" + minutes + ":" + seconds);
				timeKeeper();
				seconds -= 1;
			} 
			catch (InterruptedException e) {	
				Terminal.say("MovieProgress sleep interrupted!", e);
			}
		  }	
	   }
	}
